// pages/login/login.js

Page({

  /**
   * 页面的初始数据
   */
  data: {
    isDisabled: true,
    phone: "",
    code: "",
    name: '11',
    codeBtn: -1,
  },
  // 发送验证码
  sendCode() {
    // 如果手机号格式错误
    let verifyPhone = /^\d{11}$/.test(this.data.phone)
    if (!verifyPhone) return wx.showToast({
      title: '手机号格式错误',
      icon: "none"
    })
    // 格式正确
    wx.request({
      url: 'http://ttapi.research.itcast.cn/app/v1_0/sms/codes/' + this.data.phone,
      success: function (res) {
        console.log(res)
        if (res.statusCode == 200) {
          this.setData({
            codeBtn: 60
          })
          // 设置计时器，使得发送验证码的按钮不能被选中，并产生读秒效果
          let timer = setInterval(() => {
            if (this.data.codeBtn == -1) return clearInterval(timer)
            this.setData({
              codeBtn: this.data.codeBtn - 1
            })
          }, 1000);
        }
      }.bind(this)
    })
  },
  login(e) {
    // 登录请求
    // this.setData({
    //   phone:e.detail
    //   code:e.detail
    // })
    console.log(e);


    let query = wx.createSelectorQuery()
    query.select('.phone');

    console.log(this.data.phone)
    wx.request({
      url: 'http://ttapi.research.itcast.cn/app/v1_0/authorizations',
      method: 'POST',
      data: {
        mobile: this.data.phone,
        code: this.data.code
      },
      success: function (res) {
        console.log(res)
        // 返回code 400 时
        if (res.statusCode == 400) return wx.showToast({
          title: '手机号或验证码错误',
          icon: "none"
        })
        // 储存token
        wx.setStorageSync('token', res.data.data.token)
        wx.setStorageSync('refresh_token', res.data.data.refresh_token)
        // 获取用户信息
        // this.getUser()
        // 提示成功并返回个人页面
        setTimeout(() => {
          wx.removeStorageSync('user')
        }, 100000);
        wx.showToast({
          title: '登录成功！',
        })
        setTimeout(() => {
          wx.navigateBack({
            delta: 1,
          })
        }, 500);
      }.bind(this)
    })
  },
  // 判断form格式
  verifyRules() {
    let verifyPhone = /^\d{11}$/.test(this.data.phone)
    let verifyCode = /^\d{6}$/.test(this.data.code)
    this.setData({
      isDisabled: !(verifyPhone && verifyCode)
    })
  },
  onLoad() {
    // this.getUser()
  }
})